local PartnerInfoPanel = app.mvc.createPanelClass(...)

local ListViewVertical = require("app.widget.listview.ListViewVertical")
local PartnerListRender = import(".renders.PartnerListRender")

local PartnerHelper = require("app.partner.PartnerHelper")

local PartnerEquipPanel = import(".PartnerEquipPanel")
local PartnerLevelPanel = import(".PartnerLevelPanel")
local PartnerSkillPanel = import(".PartnerSkillPanel")
local PartnerUseExpPanel = import(".PartnerUseExpPanel")
local PartnerQualityPanel = import(".PartnerQualityPanel")

local newFloatTipsView = require("app.newFloatTips.newFloatTipsView")

local AvatarFactory = require("app.public.avatar.AvatarFactory")
--data =
function PartnerInfoPanel.createWithData(data, node)
    local sprite = PartnerInfoPanel.extend(node or cc.CSLoader:createNode(Res.PartnerInfoPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end


function PartnerInfoPanel.create(node)
    return PartnerInfoPanel.createWithData(nil, node)
end

function PartnerInfoPanel:init(data)
    self.super.init(self, data)

    self._attributeList = {}
    self:initListView()
    self:initSubTab()
    self._ui["Panel/Panel_role/AvatarTouchRect"]:setTouchEnabled(true)
    self._ui["Panel/Panel_role/AvatarTouchRect"]:addClickEventListener(function()
        self:playNextAnimation()
    end)

    self._ui["Panel/Panel_role/Panel_bom/Button"]:addClickEventListener(function()
        local p = self:getCurSelectPartner()
        if not p then
            return
        end
        if p:isHave() then
            self:gotoFight()
        else
            EM:notify(ViewEvent.Partner_OpenGetPop, p)
        end
    end)
    self._ui["Panel/Panel_role/Panel_bom/Button_1"]:addClickEventListener(function()
        self:gotoHome()
    end)
    self:registerViewEvent({
        {name = ViewEvent.Partner_DataChange, callback = handler(self, self._onPartnerDataChange)},
        {name = ViewEvent.Partner_FightTeamChange, callback = handler(self, self._onPartnerDataChange)},
        {name = ViewEvent.Partner_UseExpItem, callback = handler(self, self._onPartnerUseExpItem)},
        {name = ViewEvent.Partner_OpenUseExpPanel, callback = handler(self, self._onPartnerOpenUseExpPanel)},
        {name = ViewEvent.Partner_UseExpLongPress, callback = handler(self, self._onPartnerUseExpLongPress)},
        {name = ViewEvent.Partner_SpRewardDataChange, callback = handler(self, self._onSpRewardDataChange)},
        {name = ViewEvent.Partner_PartnerPropQuery, callback = handler(self, self._onPartnerPropQuery)},
    })

    self._ui["Panel/Panel_role/Panel_bom/Button/name"]:setString(L("text_72800001"))
    self._ui["Panel/Panel_role/Panel_bom/Button_1/name"]:setString(L("text_72800002"))

    self:getTimeline():gotoFrameAndPause(0)

    self._rolePropPanel = self._ui["Panel/Panel_role/top"]:getChildByName( "Panel" )
    self._rolePropAniState = 0
    self._rolePorpTouchLayer = self:_createRolePropTouchLayer()
    self._rolePorpTouchLayer:addClickEventListener(function(sender)
        local pos = sender:getTouchEndPosition()
        if not self._rolePropPanel:hitTest(pos.x,pos.y) then
            if self._rolePropAniState == 1 then
                self._rolePropAniState = 2
                self:getTimeline():play( "top_out",false )
                self._rolePorpTouchLayer:setVisible(false)
            end
        end
    end)
    self:addChild(self._rolePorpTouchLayer)
    self._ui["Panel/Panel_role/top"]:setVisible( false )
    self._ui["Panel/Panel_data"]:setTouchEnabled(false)
    self._ui["Panel/Panel_role/Panel_name/btn_data"]:addClickEventListener(function()
        if self._rolePropAniState == 0 then
            self._rolePropAniState = 1
            self._ui["Panel/Panel_role/top"]:setVisible( true )   
            self:getTimeline():play( "top_in", false )
            self._rolePorpTouchLayer:setVisible(true)
            local p = self:getCurSelectPartner()
            UD.partnersData:C2S_QueryPartnerProp(p:getId())
        end
    end)

    self:getTimeline():setLastFrameCallFunc(function()
        if self._rolePropAniState == 2 then
            self._rolePropAniState = 0
            self._ui["Panel/Panel_role/top"]:setVisible( false )
            self._rolePorpTouchLayer:setVisible(false)
        end
    end)
    self:reloadData()
end

-- 检查是否触发了引导
function PartnerInfoPanel:checkGuide()
    if not self:isVisible() then return end

    local funcId = Constant.FUNC_TYPE_MERCENARY
    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end

-- 获取引导node
function PartnerInfoPanel:getGuideNodeFunc(id)
    if id == 133 then
        -- 点击出战按钮
        local btn = self._ui["Panel/Panel_bom/Button"]
        if btn:isVisible() then
            return btn
        end
    end
end

function PartnerInfoPanel:_createRolePropTouchLayer()
    local floatTipBg = ccui.Layout:create()
    floatTipBg:setContentSize(display.sizeInPixels)
    floatTipBg:setBackGroundColorType(1)
    floatTipBg:setBackGroundColor(cc.c3b(0,0,0))
    floatTipBg:setOpacity(255 * 0)
    floatTipBg:setTouchEnabled(true)
    floatTipBg:setSwallowTouches(false)
    return floatTipBg
end
   

function PartnerInfoPanel:initSubTab()
    local config = {
        {key = Enums.PartnerInfoSubTab.Quality, panel = nil, btn = self._ui["Panel/Panel_data/Panel_top/Button_1"], nameLabel = self._ui["Panel/Panel_data/Panel_top/name_1"]},
        {key = Enums.PartnerInfoSubTab.Level, panel = nil, btn = self._ui["Panel/Panel_data/Panel_top/Button_2"], nameLabel = self._ui["Panel/Panel_data/Panel_top/name_2"]},
        {key = Enums.PartnerInfoSubTab.Equip, panel = nil, btn = self._ui["Panel/Panel_data/Panel_top/Button_3"], nameLabel = self._ui["Panel/Panel_data/Panel_top/name_3"]},
        {key = Enums.PartnerInfoSubTab.Skill, panel = nil, btn = self._ui["Panel/Panel_data/Panel_top/Button_4"], nameLabel = self._ui["Panel/Panel_data/Panel_top/name_4"]},
    }
    self._subTabsConfig = config
    for k ,v in pairs(config) do
        v.btn:addClickEventListener(function()
            self:onClickSubTab(k)
        end)
    end
    self:setSelectSubTab(1)
end

function PartnerInfoPanel:_createPanelByConf(conf)
    if conf.key == Enums.PartnerInfoSubTab.Level then
        conf.panel = PartnerLevelPanel.create(self._ui["Panel/Panel_data/Panel_lv"])
    elseif conf.key == Enums.PartnerInfoSubTab.Equip then
        conf.panel = PartnerEquipPanel.create(self._ui["Panel/Panel_data/Panel_equip"])
    elseif conf.key == Enums.PartnerInfoSubTab.Skill then
        conf.panel = PartnerSkillPanel.create(self._ui["Panel/Panel_data/Panel_skill"])
    elseif conf.key == Enums.PartnerInfoSubTab.Quality then
        conf.panel = PartnerQualityPanel.create(self._ui["Panel/Panel_data/Panel_quality"])
    end
end


function PartnerInfoPanel:_onPartnerOpenUseExpPanel()
    if not self._useExpPanel then
        self._useExpPanel = PartnerUseExpPanel.create(self._ui["Panel/Panel_data/Node_medicament"])
    end
    self._useExpPanel:setVisible(true)
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    self._useExpPanel:stopRenderActions()
    self._useExpPanel:setRenderParentState(true)
    self._useExpPanel:updatePartnerData(p)
    self._useExpPanel:setData(p)
    
end

function PartnerInfoPanel:hideUseExpPanel()
    if self._useExpPanel then
        self._useExpPanel:stopRenderActions()
        self._useExpPanel:setRenderParentState(false)
        self._useExpPanel:setVisible(false)
    end
end

function PartnerInfoPanel:refreshUseExpPanel(p)
    if self._useExpPanel and self._useExpPanel:isVisible() then
        if not p then
            p = self:getCurSelectPartner()
        end
        if not p then
            return
        end
        self._useExpPanel:updatePartnerData(p)
        self._useExpPanel:setData(p)  
    end
end

function PartnerInfoPanel:onClickSubTab(index)
    self:setSelectSubTab(index)
end


function PartnerInfoPanel:setSelectSubTab(index)
    if self._curSelectSubTab == index then
        return
    end

    self._curSelectSubTab = index
    local curConfig = self._subTabsConfig[index]
    if curConfig then
        local p = self:getCurSelectPartner()
        for k ,v in pairs(self._subTabsConfig) do
            if curConfig.key == v.key then
                v.btn:setEnabled(false)
                v.btn:setBright(false)
                v.nameLabel:setOpacity(255)
                if not v.panel then
                    self:_createPanelByConf(v)
                end
                v.panel:setVisible(true)
                v.panel:setData(p)

            else
                v.btn:setEnabled(true)
                v.btn:setBright(true)
                v.nameLabel:setOpacity(255 * 0.45)
                if not v.panel then
                    self:_createPanelByConf(v)
                end
                v.panel:setVisible(false)
            end
        end
    end
end


function PartnerInfoPanel:initListView()
    local params = {
		renderClass = PartnerListRender,
		perNum = 1,
		cellEventProxy = function(eventName, cellModel)
            if eventName == "click" then
                self:onChangeSelcetPartner(cellModel:getIndex())
            end
		end,
	}
    self._listview = ListViewVertical.new( self._ui["Panel/ListView"], params )
end


function PartnerInfoPanel:onChangeSelcetPartner(index)
    if not self._partners then
        return
    end
    self:hideUseExpPanel()
    self._listview:setFoucsIndex(index)
    self:_updatePartnerInfo()
end

function PartnerInfoPanel:_updatePartnerInfo()
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    self:_updateInfo(p)
    self:_updateAvatar(p)
end


function PartnerInfoPanel:_onSpRewardCountDown()
    local dt = math.floor((self._curDurationTime - app.session:getServerTime()))
    if dt > 0 then
        if dt > 24 * 60 * 60 then
            self._ui["Panel/Panel_role/time_champion/time"]:setString(string.format(L("countdowen_day"), math.floor( dt/(24*3600))))
        else
            local hour = math.floor(dt/3600)
            local min = math.floor((dt - hour*3600)/60)
            local sec = math.floor(dt - hour * 3600 - min * 60)
            self._ui["Panel/Panel_role/time_champion/time"]:setString(string.format("%02d:%02d:%02d", hour, min, sec))
        end
    else
        self._ui["Panel/Panel_role/time_champion/time"]:setString(L("lua_code_text_359"))
        self:_stopSpRewardCountDown()
    end
end

function PartnerInfoPanel:_startSpRewardCountDown(t)
   
    self:_stopSpRewardCountDown()
    self._curDurationTime = t
    self:_onSpRewardCountDown()
    self._ui["Panel/Panel_role/time_champion/time"]:schedule(handler(self, self._onSpRewardCountDown), 0.5)
end

function PartnerInfoPanel:_stopSpRewardCountDown()
    self._ui["Panel/Panel_role/time_champion/time"]:stopAllActions()
end


function PartnerInfoPanel:_updateInfo(p)
    local quality = p:getQuality()
    self._ui["Panel/Panel_role/Panel_name/name"]:setString(string.format("%s %s",p:getJobName(),p:getName()))
    self:_updateStar(p:getStar())
    self._ui["Panel/Panel_role/Panel_name/class_icon"]:loadTexture(p:getJobIcon())
    --self._ui["Panel/Panel_role/job"]:setString(p:getJobName())
    
    if p:isSpReward() then
        self._ui["Panel/Panel_role/time_champion"]:setVisible(true)
        local duration = p:getDuration()
        self:_startSpRewardCountDown(duration)
    else
        self:_stopSpRewardCountDown()
        self._ui["Panel/Panel_role/time_champion"]:setVisible(false)
    end
    -- 底部
    --[[
    self._ui["Panel/Panel_data/Panel_bom/lv"]:setString(L(Enums.QualityColorString[quality]) or "")
    local color = Enums.QualityColor[quality]
    if color then
        self._ui["Panel/Panel_data/Panel_bom/lv"]:setColor(color)
    end
    local fightNum = p:getCombatPower()

    local conf = PartnerHelper.getPartnerQualityConfigByFightNum(fightNum)
    local maxpower = conf.powerMax
    local percent = fightNum * 100/ maxpower
    if percent >= 100 then
        percent = 100
    end
    if conf.isMax then
        percent = 100
        self._ui["Panel/Panel_role/Panel_bom/Panel_bar/num"]:setString(string.format("%s", fightNum))
    else
        self._ui["Panel/Panel_role/Panel_bom/Panel_bar/num"]:setString(string.format("%s/%s", fightNum, maxpower))
    end
    self._ui["Panel/Panel_role/Panel_bom/Panel_bar/LoadingBar"]:setPercent(percent)
    --]]

    if p:isHave() then
        if p:isEquiped() then
            self._ui["Panel/Panel_role/Panel_bom/Button"]:setVisible(false)
            self._ui["Panel/Panel_role/Panel_bom/Button_1"]:setVisible(true)
        else
            self._ui["Panel/Panel_role/Panel_bom/Button"]:setVisible(true)
            self._ui["Panel/Panel_role/Panel_bom/Button_1"]:setVisible(false)
            self._ui["Panel/Panel_role/Panel_bom/Button/name"]:setString(L("text_72800001"))
        end
        self._ui["Panel/Panel_role/Panel_name/btn_data"]:setVisible(true)
        --显示战斗力
        self._ui["Panel/Panel_role/Panel_bom/text"]:setString(string.format(L("partnerString5"),p:getCombatPower()))
    else
        self._ui["Panel/Panel_role/Panel_bom/Button/name"]:setString(L("captain_tips_btn_obtain"))
        self._ui["Panel/Panel_role/Panel_bom/Button"]:setVisible(true)
   
        self._ui["Panel/Panel_role/Panel_bom/Button_1"]:setVisible(false)
        self._ui["Panel/Panel_role/Panel_name/btn_data"]:setVisible(false)
        self._ui["Panel/Panel_role/Panel_bom/text"]:setString(L("lua_code_text_359"))
    end


    local curConfig = self._subTabsConfig[self._curSelectSubTab]
    if curConfig and curConfig.panel then
        curConfig.panel:setData(p)
    end
    self:refreshUseExpPanel(p)

    if p:isHave() then
        self._ui["Panel/Panel_role/Panel_bom"]:setVisible(true)
    else
        self._ui["Panel/Panel_role/Panel_bom"]:setVisible(false)
    end

    self._ui["Panel/num"]:setString(string.format("%s/%s", UD.partnersData:getAlreadyHavePartnersCount(), #self._partners))
end


function PartnerInfoPanel:_updateAvatar(p)
    if self._curAvatar then
        if not (self._oldPartnerId and self._oldPartnerId == p:getId()) then
            self._curAvatar:removeFromParent()
            self._curAvatar = nil
        end
    end
    
    if not self._curAvatar then
        AvatarFactory.preloadPartnerByConf(p:getShowAvatorParams(), function()
            if tolua.isnull(self) then return end
            local partner = self:getCurSelectPartner()
            if self._curAvatar then
                if not (self._oldPartnerId and self._oldPartnerId == partner:getId()) then
                    self._curAvatar:removeFromParent()
                    self._curAvatar = nil
                end
            end
            
            if not self._curAvatar then
                local avatar = AvatarFactory.createPartnerByConf(partner:getShowAvatorParams())
                self._ui["Panel/Panel_role/Node_position"]:addChild(avatar)
                self._curAvatar = avatar
                self._oldPartnerId = partner:getId()
            end
           
            self._playAvatarAnimations = partner:getShowActions()
            self._playAvatarAnimationIndex = 1
            local defautAction = "mapidle"
            self._curAvatar:setScale(partner:getScale())
            if self._curAvatar:hasAnimation(defautAction) then
                self._curAvatar :getAnimation():play(defautAction)
            end
        end)
    else
        self._playAvatarAnimations = p:getShowActions()
        self._playAvatarAnimationIndex = 1
        local defautAction = "mapidle"
        if self._curAvatar:hasAnimation(defautAction) then
            self._curAvatar :getAnimation():play(defautAction)
        end
    end
end

function PartnerInfoPanel:playNextAnimation()
    if not self._curAvatar or not self._playAvatarAnimations then
        return
    end
    self._playAvatarAnimationIndex = self._playAvatarAnimationIndex + 1
    if self._playAvatarAnimationIndex <= 0 then
        self._playAvatarAnimationIndex = 1
    end
    if self._playAvatarAnimationIndex > #self._playAvatarAnimations then
        self._playAvatarAnimationIndex = 1
    end
    self._curAvatar:playAni({name=self._playAvatarAnimations[self._playAvatarAnimationIndex],playTimes = 1,next = "mapidle"})
end


function PartnerInfoPanel:_updateStar(star)
    for i =1, 5 do
        if i <= star then
            self._ui["Panel/Panel_role/Panel_name/Panel_star/s"..i]:setVisible(true)
        else
            self._ui["Panel/Panel_role/Panel_name/Panel_star/s"..i]:setVisible(false)
        end
    end
    local posx = self._ui["Panel/Panel_role/Panel_name/name"]:getPositionX()
    local size = self._ui["Panel/Panel_role/Panel_name/name"]:getContentSize()
    self._ui["Panel/Panel_role/Panel_name/Panel_star"]:setPositionX(posx + size.width)
end

function PartnerInfoPanel:getCurSelectPartner()
    if not self._partners then
        return
    end
    local focusIndex = self._listview:getFoucsIndex()
    local p = self._partners[focusIndex]
    -- assert(p ~= nil , "getCurSelectPartner p is nil")
    return p
end

function PartnerInfoPanel:reloadData(data, parmas)
    if not data then
        data = UD.partnersData:getPartnersAndSort()
    end
    self._partners = data
    self._listview:reloadData(data, parmas )
    self:_updatePartnerInfo()

    self:checkGuide()
end

function PartnerInfoPanel:onOperate(cb)
	self._onOperate = cb
end

function PartnerInfoPanel:gotoFight()
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    UD.partnersData:C2S_EmployPartner(p:getId())
end

function PartnerInfoPanel:gotoHome()
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    UD.partnersData:C2S_EmployPartner(p:getId())
end

function PartnerInfoPanel:_onPartnerDataChange()
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    self:_updateInfo(p)
    self._listview:refreshVisibleCells()

    local diffC = p:getDiffCombatPower()
    if diffC > 0 then
        local message = string.format(L("PartnerCombatPowerChange"), p:getName() ,diffC)
        p:cleanDiffCombatPower()
        display.pushToast(message)
    end
end

function PartnerInfoPanel:_onSpRewardDataChange()
    -- local data = UD.partnersData:getPartnersAndSort()
    -- self:reloadData(data)
    -- self._listview:setFoucsIndex(1)
    -- self:_updatePartnerInfo()
    self:_onPartnerDataChange()
end


function PartnerInfoPanel:_onPartnerUseExpItem(name, itemId, num)
    local p = self:getCurSelectPartner()
    if not p then
        return
    end
    UD.partnersData:C2S_LvUpPartner(p:getId(), itemId, num)
end

function PartnerInfoPanel:_onPartnerUseExpLongPress(name, curExp, maxExp, lv, state, isLevelUp)
    if self._useExpPanel then
        self._useExpPanel:updateBarByActionState(curExp, maxExp, lv, state, isLevelUp)
    end
    if isLevelUp then
        self:playEffect()
    end
end



function PartnerInfoPanel:refreshProp( proBaseAttrConf )
	proBaseAttrConf = proBaseAttrConf or {}    
    local ListView_data = self._ui["Panel/Panel_role/top"]:getChildByName( "Panel" ):getChildByName( "ListView_data" )
    -- ListView_data:removeAllItems()
    if #self._attributeList < #proBaseAttrConf then
        local num = #proBaseAttrConf - #self._attributeList
        local eachAttrNode = cc.CSLoader:createNode(Res.NewBagAttrNode) --每一条属性的节点
        local panelTemplate = eachAttrNode:getChildByName( "Panel" )
        panelTemplate:getChildByName( "num" ):setString( "" )
        for i =1, num do
            local CustomItemTemp = panelTemplate:clone()
            table.insert( self._attributeList, CustomItemTemp )
            ListView_data:pushBackCustomItem( CustomItemTemp )
        end
    end
	
    for i,v in ipairs( self._attributeList ) do
        local data = proBaseAttrConf[i]
        if data then
            v:setVisible(true)
            local name = string.gsub(L(data[1]), "：+","") or ""
            name = string.gsub(name, ":+","") or ""
            v:getChildByName( "tlt" ):setString(name)
            local num = tonumber(proBaseAttrConf[i][2])
            if num == nil then
                num = 0
            end
            if proBaseAttrConf[i][3] == 2 and num ~= 0 then
                v:getChildByName( "num" ):setString( num / 100 .. "%") -- 临时值
            elseif proBaseAttrConf[i][3] == 3 and num ~= 0 then
                local strTemp = ""
                if (num / 1000) % 1 == 0 then
                    strTemp = string.format("%.1f", num / 1000)
                else
                    strTemp = string.format("%.2f", num / 1000)
                end
                v:getChildByName( "num" ):setString(strTemp)
            else
                v:getChildByName( "num" ):setString( num ) -- 临时值
            end		
        else
            v:setVisible(false)
        end
	end
end

function PartnerInfoPanel:getAttrList()
    local p = self:getCurSelectPartner()
    if not p then
        return {}
    end
    self._showAttrList = {}
    local propShowConfs = GD:querypropShow()
    local classTemp = tostring( p:getClassId())
    for _, v in ipairs(propShowConfs) do
        if string.find( v.roleSuit, classTemp ) then
            local conf = GD:getPropConfigByName(v.propName)
            local format = 1
            if conf then
                format = tonumber(conf.format)
            end
            table.insert( self._showAttrList, { v.propName, 0 , format} )
        end
    end
	return self._showAttrList
end

function PartnerInfoPanel:_onPartnerPropQuery(event, prop)
    local showAttrList = self:getAttrList()
    local p = self:getCurSelectPartner()
    local classTemp
    if p then
        classTemp = tostring( p:getClassId())
    end
    for k, v in pairs(showAttrList) do
        if v[1] == "baseattackspeed" then
            if classTemp then
                v[2] = GD:queryProBase(classTemp).baseattackspeed
            end
		else
			local propValue = rawget(prop, v[1]) or 0
			v[2] = propValue
		end
    end
    self:refreshProp(showAttrList)
end

function PartnerInfoPanel:playEffect()
    if not self._effect then
        local effect = display.newArmature({path=Res.PartnerEffect.dir,armatureName=Res.PartnerEffect.name,animationName="",skeletonName=Res.PartnerEffect.name})
        self._ui["Panel/Panel_role/Node_position"]:addChild(effect)
        self._effect = effect
    end
    --leftClampEffect:setPositionX(x)
    -- if self._effect:getAnimation():isPlaying() then
    --     return
    -- end
    self._effect:getAnimation():gotoAndPlay("YBguang")
    if self.armatureNode then
        self.armatureNode:playAni({name="talk",playTimes = 1,next = "mapidle",completeCallback = function()
            self:playNextAnimation()
        end}) 
    end
end

return PartnerInfoPanel